import MapItem from './mapItem.js'

import mapSettings from './mapSettings.js'

class Map extends Laya.Sprite {
  constructor (options = {}) {
    super()
    this.init(options)
  }

  init (options = {}) {
    // 初始化引擎对象以及设定
    this.initLayas()

    // 初始化地图基本属性
    this.id = options.id
    this.name = options.name
    this.rowNum = options.rowNum
    this.colNum = options.colNum
    this.items = []

    // 生成地图区块，放入每个区块
    for (let i = 0; i < this.rowNum; i++) {
      for (let j = 0; j < this.colNum; j++) {
        const index = i * this.rowNum + j
        const itemOptions = options.items[index]
        // 创建对象并且加载资源
        const item = new MapItem(index, itemOptions, this)
        this.items.push(item)
      }
    }
  }


  // 初始化引擎对象以及设定
  initLayas () {
    // 地图尺寸，必须与UI编辑器中的值保持一致
    this.size(mapSettings.MAP_VIEW_SIZE, mapSettings.MAP_VIEW_SIZE)

    // 初始化全景图片层
    this.bgImage = new Laya.Image()
    this.bgImage.size(mapSettings.MAP_VIEW_SIZE, mapSettings.MAP_VIEW_SIZE)
    this.addChild(this.bgImage)

    // 初始化单位容器
    this.layer = new Laya.Panel()
    this.layer.size(this.colNum * mapSettings.MAP_ITEM_SIZE, this.rowNum * mapSettings.MAP_ITEM_SIZE)
    this.addChild(this.layer)
    // 初始化角色层,默认zOrder为15
    this.roleLayer = new Laya.Sprite()
    this.roleLayer.size(this.colNum * mapSettings.MAP_ITEM_SIZE, this.rowNum * mapSettings.MAP_ITEM_SIZE)
    this.roleLayer.zOrder = 15
    this.layer.addChild(this.roleLayer)

    // 初始化遮罩图片层
    this.coverImage = new Laya.Image()
    this.coverImage.size(mapSettings.MAP_VIEW_SIZE, mapSettings.MAP_VIEW_SIZE)
    this.addChild(this.coverImage)
  }

  // 激活地图资源
  async initSrc () {
    const len = this.items.length
    for (let i = 0; i < len; i++) {
      const item = this.items[i]
      await item.initSrc()
    }
  }
}

export default Map